﻿#include "ssTextureSpirit2d.h"
#ifdef SS_USE_WXWIDGETS
#include "../texture/ssWXPicture.h"
#else
#include "../texture/ssTgaPicture.h"
#endif


namespace StarSeeker
{

ssTextureSpirit2d::ssTextureSpirit2d(const char* name)
	:ssIRes(name)
{
	m_type = SS_RES_PICTURE;
	m_width = 0;
	m_height = 0;
	m_glID = SS_INVAILD_U32;
	m_glImageFormat = 0;
	m_glInternalFormat = GL_RGBA;
}

ssTextureSpirit2d::~ssTextureSpirit2d()
{
	UnLoad();
}

bool ssTextureSpirit2d::LoadFromFile(const char* path)
{
	if (m_glID != SS_INVAILD_U32)
	{
		return false;
	}
#ifdef SS_USE_WXWIDGETS
	ssIPicture* pp = new ssWXPicture();
#else
	ssIPicture* pp = new ssTargaImage();
#endif
	if (pp->LoadFromFile(path))
	{
		m_width = pp->m_width;
		m_height = pp->m_height;
		m_glImageFormat = pp->m_glImageFormat;
		glGenTextures(1, &m_glID);
		glBindTexture(GL_TEXTURE_2D, m_glID);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexImage2D(GL_TEXTURE_2D, 0, m_glInternalFormat, m_width, m_height, 0, m_glImageFormat, GL_UNSIGNED_BYTE, pp->m_pBit);
		glBindTexture(GL_TEXTURE_2D, 0);

		delete pp;
		return true;
	}
	delete pp;
	return false;
}

bool ssTextureSpirit2d::CreateEmpty(i32 width, i32 height)
{
	if (m_glID != SS_INVAILD_U32)
	{
		return false;
	}
	//f32* bit = new f32[width*height*4];
	//for (u32 i=0; i<width*height*4; ++i)
	//{
	//	bit[i] = 1.0f;
	//}
	m_width = width;
	m_height = height;
	m_glImageFormat = GL_RGBA;
	glGenTextures(1, &m_glID);
	glBindTexture(GL_TEXTURE_2D, m_glID);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexImage2D(GL_TEXTURE_2D, 0, m_glInternalFormat, m_width, m_height, 0, m_glImageFormat, GL_FLOAT, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
	//delete[] bit;
	return true;
}

void ssTextureSpirit2d::Use()
{
	glBindTexture(GL_TEXTURE_2D, m_glID);
}

void ssTextureSpirit2d::Nonuse()
{
	glBindTexture(GL_TEXTURE_2D, 0);
}

void ssTextureSpirit2d::UnLoad()
{
	if (m_glID != SS_INVAILD_U32)
	{
		glDeleteTextures(1, &m_glID);
		m_glID = SS_INVAILD_U32;
	}
}

StarSeeker::u32 ssTextureSpirit2d::GetHandle()
{
	return m_glID;
}

}
